package com.zzs.common.sms.service.impl;

import com.alibaba.fastjson2.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.zzs.common.sms.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zzs
 * @date 2025/03/24
 */
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {
    @Autowired
    private Client client;

    // 短信模板
    @Value("${sms.aliyun.templateCode}")
    private String templateCode;

    // 短信签名
    @Value("${sms.aliyun.signName}")
    private String signName;

    @Override
    public boolean sendSmsCode(String phone, String code) {
        Map<String, String> params = new HashMap<>();
        params.put("code", code);
        return sendSmsCode(phone, params);
    }

    private boolean sendSmsCode(String phone, Map<String, String> params) {
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phone);
        request.setSignName(signName);
        request.setTemplateCode(templateCode);
        request.setTemplateParam(JSON.toJSONString(params));
        try {
            SendSmsResponse response = client.sendSms(request);
            SendSmsResponseBody body = response.getBody();
            return "OK".equalsIgnoreCase(body.getCode());
        } catch (Exception e) {
            log.error("短信 {} 发送失败，失败原因: {}", JSON.toJSONString(request), e.getMessage());
            return false;
        }
    }
}
